package com.hqyj.am.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.am.config.EmailSend;
import com.hqyj.am.dao.UserMapper;
import com.hqyj.am.pojo.ResultVo;
import com.hqyj.am.pojo.User;
import com.hqyj.am.service.EmailService;
import com.hqyj.am.util.MDFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author: chenglongfei
 * @date: 2022/8/18
 * @Description EmailServiceImpl
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    EmailSend emailSend;

    @Override
    public ResultVo emailSend(String email) {
        ResultVo vo = new ResultVo();
        if (emailSend.send(email)){
            vo.setInfo("短信发送成功");
            vo.setSuccess(true);
        }else {
            vo.setInfo("短信发送失败");
        }

        return vo;
    }

    @Override
    public ResultVo emailChange(User user) {
        ResultVo rv = new ResultVo();
        //判断缓存中是否存在验证码的键名
        Object obj = redisTemplate.opsForValue().get("code:"+user.getEmail());
        System.out.println(obj);
        if (obj==null){
            rv.setInfo("验证码超时失效");
        }else {
            if (obj.equals(user.getCode())){
                rv.setInfo("验证码输入正确");
                rv.setSuccess(true);
            }else {
                rv.setInfo("验证码输入错误");
            }
        }
        return rv;
    }

    @Override
    public ResultVo emailSave(User user) {
        ResultVo rv = new ResultVo();
        //为了密码安全性,盐值从新生成
        String salt = UUID.randomUUID()+"";
        MDFive mdFive = new MDFive();
        //加密新密码
        String pwd= mdFive.encrypt(user.getUserPwd(),salt);
        user.setUserPwd(pwd);
        //修改密码数据操作
        //创建条件构造器对象
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //邮箱条件修改
//        queryWrapper.eq("email",user.getEmail());
        //根据userId修改
        int num = userMapper.updateById(user);
        //修改
//        int num = userMapper.update(user, queryWrapper);
        if (num >0) {
            rv.setInfo("修改成功");
            rv.setSuccess(true);
        }else {
            rv.setInfo("修改失败");
        }
        return rv;
    }

}
